package com.ibm.risk.irmp.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XlsxUtils {

    public static void calculate(Workbook wb) {
        XSSFWorkbook xWb = (XSSFWorkbook) wb;
        //公式重新计算
        xWb.getCreationHelper().createFormulaEvaluator().evaluateAll();
        XSSFSheet sheet = xWb.getSheetAt(0);
        int firstRowNum = sheet.getFirstRowNum();
        int lastRowNum = sheet.getLastRowNum();
        for (int r = firstRowNum; r < lastRowNum; r++) {
            XSSFRow row = sheet.getRow(r);
            if (row != null) {
                short firstCellNum = row.getFirstCellNum();
                short lastCellNum = row.getLastCellNum();
                for (int col = firstCellNum; col < lastCellNum; col++) {
                    XSSFCell cell = row.getCell(col);
                    xWb.getCreationHelper().createFormulaEvaluator().evaluateFormulaCell(cell);
                }
            }
        }

        //计算Excel文件的所有公式
        HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
    }

    /**
     * 描述：根据文件后缀，自适应Excel文件的版本
     */
    public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook wb = null;
        String fileExtName = fileName.substring(fileName.lastIndexOf("."));
        if (fileName.endsWith(".xls")) {
            wb = new HSSFWorkbook(inStr); // 2003-
        } else if (fileName.endsWith(".xlsx")) {
            wb = new XSSFWorkbook(inStr); // 2007+
        } else {
            throw new RuntimeException("解析的文件格式有误！");
        }
        return wb;
    }

    public static String getCellStrValue(Cell cell) {
        if (cell == null) {
            return null;
        }

        String cellValue = "";
        // 以下是判断数据的类型
        switch (cell.getCellType()) {
            case NUMERIC: // 数字
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    cellValue = sdf.format(org.apache.poi.ss.usermodel.DateUtil.getJavaDate(cell.getNumericCellValue())).toString();
                } else {
                    DataFormatter dataFormatter = new DataFormatter();
                    cellValue = dataFormatter.formatCellValue(cell);
                }
                break;
            case STRING: // 字符串
                cellValue = cell.getStringCellValue();
                break;
            case BOOLEAN: // Boolean
                cellValue = cell.getBooleanCellValue() + "";
                break;
            case FORMULA: // 公式
                cellValue = cell.getCellFormula() + "";
                break;
            case BLANK: // 空值
                cellValue = "";
                break;
            case ERROR: // 故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }

    public static boolean isGreyCell(Cell cell) {
        XSSFCellStyle cellStyle = (XSSFCellStyle) cell.getCellStyle();
        XSSFColor fgColor = cellStyle.getFillForegroundColorColor();
        int[] bgRGB = new int[3];
        if (fgColor != null) {
            byte[] xssfColorBytes = fgColor.getRGBWithTint();
            if (xssfColorBytes != null && xssfColorBytes.length >= 3) {
                bgRGB[0] = Byte.toUnsignedInt(xssfColorBytes[0]);
                bgRGB[1] = Byte.toUnsignedInt(xssfColorBytes[1]);
                bgRGB[2] = Byte.toUnsignedInt(xssfColorBytes[2]);
                if (bgRGB[0] == bgRGB[1] && bgRGB[0] == bgRGB[2]) {
                    return bgRGB[0] <= 0xf0 && bgRGB[0] >= 0x90;
                }
            }
        }
        return false;
    }

    public static String getCellFgColor(Cell cell) {
        XSSFCellStyle cellStyle = (XSSFCellStyle) cell.getCellStyle();
        XSSFColor fgColor = cellStyle.getFillForegroundColorColor();
        int[] bgRGB = new int[]{255, 255, 255};
        if (fgColor != null) {
            byte[] xssfColorBytes = fgColor.getRGBWithTint();
            if (xssfColorBytes != null && xssfColorBytes.length >= 3) {
                bgRGB[0] = Byte.toUnsignedInt(xssfColorBytes[0]);
                bgRGB[1] = Byte.toUnsignedInt(xssfColorBytes[1]);
                bgRGB[2] = Byte.toUnsignedInt(xssfColorBytes[2]);
                if (fgColor.isAuto() == false) {
                    cellStyle.setFillForegroundColor(new XSSFColor(xssfColorBytes, null));
                    cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                }
            }
        }
        String strColor = String.format("#%02X%02X%02X", bgRGB[0], bgRGB[1], bgRGB[2]);
        return strColor;
    }

    public static Workbook getWorkbook(File templateFile) throws Exception {
        try (InputStream fis = new FileInputStream(templateFile)) {
            Workbook workbook = getWorkbook(fis, templateFile.getName());
            if (null == workbook) {
                if (fis != null) fis.close();
                throw new RuntimeException("Excel模板不存在");
            }
            return workbook;
        }
    }

    public static String readExcelToHtml(Workbook wb, boolean isWithStyle) {
        String htmlExcel = "";
        XSSFWorkbook xwb = (XSSFWorkbook) wb;

        //公式重新计算
        calculate(wb);

        htmlExcel = getExcelInfo(xwb, isWithStyle);
        return htmlExcel;
    }

    public static double getCellDoubleValue(XSSFCell cell) {
        if (cell == null) {
            return 0d;
        }
        // 以下是判断数据的类型
        switch (cell.getCellType()) {
            case FORMULA:
            case NUMERIC: // 数字
                return (int) cell.getNumericCellValue();
            case STRING: // 字符串
                String cellValue = cell.getStringCellValue();
                return Integer.valueOf(cellValue);
            case BOOLEAN: // Boolean
                break;
            case ERROR: // 故障
                break;
            default:
                break;
        }
        throw new RuntimeException("Cell [" + cell.getRowIndex() + ", " + cell.getColumnIndex() + "] Value Extract Error:" + cell);
    }

    /**
     * 获取表格单元格Cell内容   String value = sheet.getCell(colIndex, rowIndex).getContents() Excel的空值时取出为""
     *
     * @param cell
     * @return
     */
    protected static String getCellValue(XSSFCell cell) {
        DecimalFormat percentFormat1 = new DecimalFormat("##0.00%");
        DecimalFormat percentFormat2 = new DecimalFormat("##0%");
        DecimalFormat decimalFormat = new DecimalFormat("###,###,###,###,##0.00");
        DecimalFormat integerFormat = new DecimalFormat("0");
        String result = new String();
        if (cell == null) {
            return result;
        }
        try {
            switch (cell.getCellType()) {
                case FORMULA:
                    //System.out.println(cell.getRowIndex() + " ," + cell.getColumnIndex());
                    if (cell.getRawValue().startsWith("#")) {
                        result = cell.getRawValue();
                    } else {
                        if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("0.00%")) {//9
                            //百分数
                            double value = cell.getNumericCellValue();
                            result = percentFormat1.format(value);
                        } else if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("0%")) {//9
                            //百分数
                            double value = cell.getNumericCellValue();
                            result = percentFormat2.format(value);
                        } else if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("@")) {
                            //text格式
                            result = cell.getRawValue();
                        } else if (cell.getHyperlink() != null) {
                            result = String.format("<a href='%s'>%s</a>", cell.getHyperlink().getAddress(), cell.getRawValue());
                        } else if (cell.getCellStyle().getDataFormat() == 1 || cell.getCellStyle().getDataFormat() == 176
                                || cell.getCellStyle().getDataFormat() == 177) {
                            if (StringUtils.indexOf(cell.getCellStyle().getDataFormatString(), "0.0") < 0) {
                                // Integer 整数
                                result = integerFormat.format(cell.getNumericCellValue());
                            } else {
                                result = decimalFormat.format(cell.getNumericCellValue());
                            }
                        } else {
                            //result = cell.getRawValue();
                            //double value = cell.getNumericCellValue();
                            CellStyle style = cell.getCellStyle();
                            String temp = style.getDataFormatString();
                            result = decimalFormat.format(cell.getNumericCellValue());
                        }
                    }
                    break;
                case NUMERIC: // Cell.CELL_TYPE_NUMERIC:// 数字类型
                    if (DateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
                        SimpleDateFormat sdf = null;
                        if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
                            sdf = new SimpleDateFormat("HH:mm");
                        } else {// 日期
                            sdf = new SimpleDateFormat("yyyy-MM-dd");
                        }
                        Date date = cell.getDateCellValue();
                        result = sdf.format(date);
                    } else if (cell.getCellStyle().getDataFormat() == 1) {
                        // Integer 整数
                        result = integerFormat.format(cell.getNumericCellValue());
                    } else if (cell.getCellStyle().getDataFormat() == 58) {
                        // 处理自定义日期格式：m月d日(通过判断单元格的格式id解决，id的值是58)
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        double value = cell.getNumericCellValue();
                        Date date = org.apache.poi.ss.usermodel.DateUtil
                                .getJavaDate(value);
                        result = sdf.format(date);
                    } else if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("0.00%")) { //9
                        //百分数
                        double value = cell.getNumericCellValue();
                        result = percentFormat1.format(value);
                    } else if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("0%")) { //9
                        //百分数
                        double value = cell.getNumericCellValue();
                        result = percentFormat2.format(value);
                    } else {
                        double value = cell.getNumericCellValue();
                        CellStyle style = cell.getCellStyle();
                        String temp = style.getDataFormatString();
                        // 单元格设置成常规
                        if (cell.getColumnIndex() < 2) {
                            decimalFormat.applyPattern("#");
                        }
                        result = decimalFormat.format(value);
                    }
                    break;
                case STRING: // Cell.CELL_TYPE_STRING:
                    // String类型
                    result = cell.getRichStringCellValue().toString();
                    result = result.replaceAll(" ", "&nbsp;");
                    break;
                case BLANK: // Cell.CELL_TYPE_BLANK:
                    result = "";
                    break;
                default:
                    result = "";
                    break;
            }
        } catch (Exception exp) {
            throw new RuntimeException("Cell [" + cell.getRowIndex() + ", " + cell.getColumnIndex() + "] Value Extract Error:" + cell, exp);
        }
        return result;
    }

    /**
     * 读取excel成string
     *
     * @param wb
     * @param isWithStyle
     * @return
     */
    public static String getExcelInfo(XSSFWorkbook wb, boolean isWithStyle) {

        StringBuffer sb = new StringBuffer();
        XSSFSheet sheet = wb.getSheetAt(0);//获取第一个Sheet的内容
        // map等待存储excel图片
        Map<String, PictureData> sheetIndexPicMap = getSheetPictrues(0, sheet, wb);
        //临时保存位置，正式环境根据部署环境存放其他位置
//        try {
//            if(sheetIndexPicMap != null)
//                printImg(sheetIndexPicMap);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        //读取excel拼装html
        int lastRowNum = sheet.getLastRowNum();
        Map<String, Object>[] map = getRowSpanColSpanMap(sheet);
        //sb.append("<table id='report1' style='border-collapse:collapse;width:100%;zoom:60%;'>");
        //sb.append("<table id='report1' style='border-collapse:collapse;width:$$MAX_ROW_WIDTH$$;zoom:80%;'>");
        sb.append("<table id='report1' style='border-collapse:collapse;width:$$MAX_ROW_WIDTH$$;zoom:100%;'>");
        XSSFRow row = null;      //兼容
        XSSFCell cell = null;    //兼容
        int[] colsOfTable = getColsOfTable(sheet); //TODO 多余？
        int lastColNum = colsOfTable[0];
        int rowHeight = colsOfTable[1];

        int maxRowWidth = 0;
        for (int rowNum = sheet.getFirstRowNum(); rowNum <= lastRowNum; rowNum++) {
            if (rowNum > 1000) break;
            row = sheet.getRow(rowNum);


            if (null != row) {
                lastColNum = row.getLastCellNum();
                rowHeight = row.getHeight();
            } else {
                sb.append("<tr><td >  </td></tr>");
                continue;
            }

            if (row.getZeroHeight() || 0 == rowHeight) {
                //针对jxl的隐藏行（此类隐藏行只是把高度设置为0，单getZeroHeight无法识别）
                continue;
            }
            sb.append("<tr>");

            int rowWidth = 0;
            for (int colNum = 0; colNum < lastColNum; colNum++) {
                if (sheet.isColumnHidden(colNum)) continue;
                String imageRowNum = "0_" + rowNum + "_" + colNum;
                String imageHtml = "";
                cell = row.getCell(colNum);
                if ((sheetIndexPicMap != null && !sheetIndexPicMap.containsKey(imageRowNum) || sheetIndexPicMap == null)
                        && cell == null) {
                    //特殊情况 空白的单元格会返回null+
                    sb.append("<td>  </td>");
                    continue;
                }
                //判断该单元格是否包含图片，为空时也可能包含图片
                if (sheetIndexPicMap != null && sheetIndexPicMap.containsKey(imageRowNum)) {
                    //图片路径
                    //PictureData pictureData = sheetIndexPicMap.get(imageRowNum);
                    //String imageFileName =  "/images/" + imageRowNum + "_" +  System.nanoTime() + "." + pictureData.suggestFileExtension();
                    //saveImgFile(pictureData, httpAccessableImagePath + imageFileName);

                    //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                    //String serverPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
                    //String imagePath = serverPath + imageFileName;
                    //imageHtml = "<img src='" + imagePath + "' style='height:" + rowHeight / 1.5 + "px;'>";
                }
                String stringValue = getCellValue(cell);
                if (map[0].containsKey(rowNum + "," + colNum)) {
                    String pointString = (String) map[0].get(rowNum + "," + colNum);
                    int bottomeRow = Integer.valueOf(pointString.split(",")[0]);
                    int bottomeCol = Integer.valueOf(pointString.split(",")[1]);
                    int rowSpan = bottomeRow - rowNum + 1;
                    int colSpan = bottomeCol - colNum + 1;
                    if (map[2].containsKey(rowNum + "," + colNum)) {
                        rowSpan = rowSpan - (Integer) map[2].get(rowNum + "," + colNum);
                    }
                    sb.append("<td rowspan= '" + rowSpan + "' colspan= '" + colSpan + "' ");
                    if (map.length > 3 && map[3].containsKey(rowNum + "," + colNum)) {
                        //此类数据首行被隐藏，value为空，需使用其他方式获取值
                        stringValue = getMergedRegionValue(sheet, rowNum, colNum);
                    }
                } else if (map[1].containsKey(rowNum + "," + colNum)) {
                    map[1].remove(rowNum + "," + colNum);
                    continue;
                } else {
                    sb.append("<td ");
                }

                //判断是否需要样式
                if (isWithStyle) {
                    dealExcelStyle(wb, sheet, cell, sb, map);        //处理单元格样式

                    //TODO 汇总时合并单元格会计算多次
                    rowWidth += calcCellWidth(wb, sheet, cell, map); //计算单元格宽度
                }

                sb.append(">");
                if (sheetIndexPicMap != null && sheetIndexPicMap.containsKey(imageRowNum)) sb.append(imageHtml);
                if (stringValue == null || "".equals(stringValue.trim())) {
                    sb.append("   ");
                } else {
                    // 将ascii码为160的空格转换为html下的空格（ ）
                    sb.append(stringValue.replace(String.valueOf((char) 160), " "));
                }
                sb.append("</td>");
            }

            if (maxRowWidth < rowWidth) {
                maxRowWidth = rowWidth;
            }

            sb.append("</tr>");
            continue;
        }
        sb.append("</table>");

        //替换表个宽度
        return sb.toString().replace("$$MAX_ROW_WIDTH$$", maxRowWidth + "px");
    }

    private static int[] getColsOfTable(Sheet sheet) {

        int[] data = {0, 0};
        for (int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum(); i++) {
            if (null != sheet.getRow(i)) {
                data[0] = sheet.getRow(i).getLastCellNum();
                data[1] = sheet.getRow(i).getHeight();
                break;
            }
        }
        return data;
    }

    /**
     * 获取Excel图片公共方法
     *
     * @param sheetNum 当前sheet编号
     * @param sheet    当前sheet对象
     * @param workbook 工作簿对象
     * @return Map key:图片单元格索引（0_1_1）String，value:图片流PictureData
     */
    public static Map<String, PictureData> getSheetPictrues(int sheetNum, Sheet sheet, Workbook workbook) {
        if (workbook instanceof HSSFWorkbook) {
            return getSheetPictrues03(sheetNum, (HSSFSheet) sheet, (HSSFWorkbook) workbook);
        } else if (workbook instanceof XSSFWorkbook) {
            return getSheetPictrues07(sheetNum, (XSSFSheet) sheet, (XSSFWorkbook) workbook);
        } else {
            return null;
        }
    }

    /**
     * 获取Excel2003图片
     *
     * @param sheetNum 当前sheet编号
     * @param sheet    当前sheet对象
     * @param workbook 工作簿对象
     * @return Map key:图片单元格索引（0_1_1）String，value:图片流PictureData
     * @throws IOException
     */
    private static Map<String, PictureData> getSheetPictrues03(int sheetNum, HSSFSheet sheet, HSSFWorkbook workbook) {

        Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
        List<HSSFPictureData> pictures = workbook.getAllPictures();
        if (pictures.size() != 0) {
            for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) {
                HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
                shape.getLineWidth();
                if (shape instanceof HSSFPicture) {
                    HSSFPicture pic = (HSSFPicture) shape;
                    int pictureIndex = pic.getPictureIndex() - 1;
                    HSSFPictureData picData = pictures.get(pictureIndex);
                    String picIndex = String.valueOf(sheetNum) + "_"
                            + String.valueOf(anchor.getRow1()) + "_"
                            + String.valueOf(anchor.getCol1());
                    sheetIndexPicMap.put(picIndex, picData);
                }
            }
            return sheetIndexPicMap;
        } else {
            return null;
        }
    }

    /**
     * 获取Excel2007图片
     *
     * @param sheetNum 当前sheet编号
     * @param sheet    当前sheet对象
     * @param workbook 工作簿对象
     * @return Map key:图片单元格索引（0_1_1）String，value:图片流PictureData
     */
    private static Map<String, PictureData> getSheetPictrues07(int sheetNum, XSSFSheet sheet, XSSFWorkbook workbook) {
        Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();

        try {
            for (POIXMLDocumentPart dr : sheet.getRelations()) {
                if (dr instanceof XSSFDrawing) {
                    XSSFDrawing drawing = (XSSFDrawing) dr;
                    List<XSSFShape> shapes = drawing.getShapes();
                    for (XSSFShape shape : shapes) {
                        if (shape instanceof XSSFPicture) {
                            XSSFPicture pic = (XSSFPicture) shape;
                            XSSFClientAnchor anchor = pic.getPreferredSize();
                            CTMarker ctMarker = anchor.getFrom();
                            String picIndex = String.valueOf(sheetNum) + "_" + ctMarker.getRow() + "_" + ctMarker.getCol();
                            sheetIndexPicMap.put(picIndex, pic.getPictureData());
                        }
                    }

                    List<XSSFChart> charts = drawing.getCharts();
                    for (XSSFChart chart : charts) {
                        String name = chart.getGraphicFrame().getName();

                        //TODO 将chart保存为图片
                        System.out.println("chart title:       " + chart.getTitleText().getString());
//                        XSSFDrawing drawing1 = chart.getGraphicFrame().getDrawing();
//                        List<XSSFShape> shapes1 = drawing1.getShapes();

//                        PackagePart packagePart = chart.getGraphicFrame().getDrawing().getPackagePart();
////                        InputStream inputStream = packagePart.getInputStream();
//
//                        OutputStream outputStream = new FileOutputStream(new File("/tmp/image.png"));
//
//
//                        packagePart.save(outputStream);

//                        int count = 0;
//                        byte[] data = new byte[1024];
//                        while ((count = inputStream.read(data, 0, data.length)) != -1) {
//                            outputStream.write(data);
//                        }
//                        inputStream.close();
//                        outputStream.close();
                    }
                }
            }
        } catch (Exception exp) {
            exp.printStackTrace();
        }

        return sheetIndexPicMap;
    }

    /**
     * 分析excel表格，记录合并单元格相关的参数，用于之后html页面元素的合并操作
     *
     * @param sheet
     * @return
     */
    private static Map<String, Object>[] getRowSpanColSpanMap(Sheet sheet) {
        Map<String, Object> map0 = new HashMap<>();    //保存合并单元格的对应起始和截止单元格
        Map<String, Object> map1 = new HashMap<>();    //保存被合并的那些单元格
        Map<String, Object> map2 = new HashMap<>();    //记录被隐藏的单元格个数
        Map<String, Object> map3 = new HashMap<>();    //记录合并了单元格，但是合并的首行被隐藏的情况
        int mergedNum = sheet.getNumMergedRegions();
        CellRangeAddress range = null;
        Row row = null;
        for (int i = 0; i < mergedNum; i++) {
            range = sheet.getMergedRegion(i);
            int topRow = range.getFirstRow();
            int topCol = range.getFirstColumn();
            int bottomRow = range.getLastRow();
            int bottomCol = range.getLastColumn();
            /**
             * 此类数据为合并了单元格的数据
             * 1.处理隐藏（只处理行隐藏，列隐藏poi已经处理）
             */
            if (topRow != bottomRow) {
                int zeroRoleNum = 0;
                int tempRow = topRow;
                for (int j = topRow; j <= bottomRow; j++) {
                    row = sheet.getRow(j);
                    if (row.getZeroHeight() || row.getHeight() == 0) {
                        if (j == tempRow) {
                            //首行就进行隐藏，将rowTop向后移
                            tempRow++;
                            //由于top下移，后面计算rowSpan时会扣除移走的列，所以不必增加zeroRoleNum;
                            continue;
                        }
                        zeroRoleNum++;
                    }
                }
                if (tempRow != topRow) {
                    map3.put(tempRow + "," + topCol, topRow + "," + topCol);
                    topRow = tempRow;
                }
                if (zeroRoleNum != 0) map2.put(topRow + "," + topCol, zeroRoleNum);
            }
            map0.put(topRow + "," + topCol, bottomRow + "," + bottomCol);
            int tempRow = topRow;
            while (tempRow <= bottomRow) {
                int tempCol = topCol;
                while (tempCol <= bottomCol) {
                    map1.put(tempRow + "," + tempCol, topRow + "," + topCol);
                    tempCol++;
                }
                tempRow++;
            }
            map1.remove(topRow + "," + topCol);
        }
        Map<String, Object>[] map = new Map[]{map0, map1, map2, map3};
//        System.err.println(map0);
        return map;
    }

    /**
     * 获取合并单元格的值
     *
     * @param sheet
     * @param row
     * @param column
     * @return
     */
    public static String getMergedRegionValue(XSSFSheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress ca = sheet.getMergedRegion(i);
            int firstColumn = ca.getFirstColumn();
            int lastColumn = ca.getLastColumn();
            int firstRow = ca.getFirstRow();
            int lastRow = ca.getLastRow();

            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    XSSFRow fRow = sheet.getRow(firstRow);
                    XSSFCell fCell = fRow.getCell(firstColumn);
                    return getCellValue(fCell);
                }
            }
        }
        return null;
    }

    /**
     * 处理表格样式
     *
     * @param wb
     * @param sheet
     * @param cell
     * @param sb
     */
    private static void dealExcelStyle(Workbook wb, Sheet sheet, Cell cell, StringBuffer sb, Map<String, Object>[] map) {
        if (cell == null) {
            return;
        }
        CellStyle cellStyle = cell.getCellStyle();
        if (cellStyle != null) {
            short alignment = cellStyle.getAlignment().getCode();
            sb.append("align='" + convertAlignToHtml(alignment) + "' ");//单元格内容的水平对齐方式
            short verticalAlignment = cellStyle.getVerticalAlignment().getCode();
            sb.append("valign='" + convertVerticalAlignToHtml(verticalAlignment) + "' ");//单元格中内容的垂直排列方式

            if (wb instanceof XSSFWorkbook) {

                XSSFFont xf = ((XSSFCellStyle) cellStyle).getFont();
                //short boldWeight = xf.getBoldweight();
                boolean isBold = xf.getBold();
                sb.append("style='");
                //sb.append("font-weight:" + boldWeight + ";"); // 字体加粗
                if (isBold) {
                    sb.append("font-weight: bold;"); // 字体加粗
                }
//                sb.append("font-size: " + xf.getFontHeight() / 2 + "%;"); // 字体大小

                int topRow = cell.getRowIndex(), topColumn = cell.getColumnIndex();
                if (map[0].containsKey(topRow + "," + topColumn)) {
                    //该单元格为合并单元格，宽度需要获取所有单元格宽度后合并
                    String value = (String) map[0].get(topRow + "," + topColumn);
                    String[] ary = value.split(",");
                    int bottomColumn = Integer.parseInt(ary[1]);
                    if (topColumn != bottomColumn) {
                        //合并列，需要计算相应宽度
                        int columnWidth = 0;
                        for (int i = topColumn; i <= bottomColumn; i++) {
                            columnWidth += sheet.getColumnWidth(i);
                        }
                        sb.append("width:" + columnWidth / 256 * xf.getFontHeight() / 20 + "pt;");
                    } else {
                        int columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
                        sb.append("width:" + columnWidth / 256 * xf.getFontHeight() / 20 + "pt;");
                    }
                } else {
                    int columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
                    sb.append("width:" + columnWidth / 256 * xf.getFontHeight() / 20 + "pt;");
                }

                XSSFColor xc = xf.getXSSFColor();
                if (xc != null && !"".equals(xc.toString()) && xc.getARGBHex() != null) {
                    sb.append("color:#" + xc.getARGBHex().substring(2) + ";"); // 字体颜色
                }

                XSSFColor bgColor = (XSSFColor) cellStyle.getFillForegroundColorColor();
                if (bgColor != null && !"".equals(bgColor.toString())) {
                    sb.append("background-color:#" + bgColor.getARGBHex().substring(2) + ";"); // 背景颜色
                }
                //sb.append("border:solid #000000 1px;");
                //sb.append(getBorderStyle(0,cellStyle.getBorderTop(), ((XSSFCellStyle) cellStyle).getTopBorderXSSFColor()));
                //sb.append(getBorderStyle(1,cellStyle.getBorderRight(), ((XSSFCellStyle) cellStyle).getRightBorderXSSFColor()));
                //sb.append(getBorderStyle(2,cellStyle.getBorderBottom(), ((XSSFCellStyle) cellStyle).getBottomBorderXSSFColor()));
                //sb.append(getBorderStyle(3,cellStyle.getBorderLeft(), ((XSSFCellStyle) cellStyle).getLeftBorderXSSFColor()));
//                setBorder.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
//                setBorder.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
//                setBorder.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
//                setBorder.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
                //TODO 解析边框不准确
                if (bgColor == null && cellStyle.getBorderTop().getCode() == BorderStyle.NONE.getCode()) {
                    sb.append("border-top:solid #fff 1px;");
                } else {
                    sb.append("border-top:solid #000000 1px;");
                }
                if (bgColor == null && cellStyle.getBorderRight().getCode() == BorderStyle.NONE.getCode()) {
                    //sb.append("border-right:solid #fff 1px;");
                } else {
                    sb.append("border-right:solid #000000 1px;");
                }
                if (bgColor == null && cellStyle.getBorderBottom().getCode() == BorderStyle.NONE.getCode()) {
                    //sb.append("border-bottom:solid #fff 1px;");
                } else {
                    sb.append("border-bottom:solid #000000 1px;");
                }
                if (bgColor == null && cellStyle.getBorderLeft().getCode() == BorderStyle.NONE.getCode()) {
                    sb.append("border-left:solid #fff 1px;");
                } else {
                    sb.append("border-left:solid #000000 1px;");
                }
            }
//            }else if(wb instanceof HSSFWorkbook){
//                HSSFFont hf = ((HSSFCellStyle) cellStyle).getFont(wb);
//                //short boldWeight = hf.getBoldweight();
//                boolean isBold = hf.getBold();
//                short fontColor = hf.getColor();
//                sb.append("style='");
//
//                HSSFPalette palette = ((HSSFWorkbook) wb).getCustomPalette();
//                // 类HSSFPalette用于求的颜色的国际标准形式
//                HSSFColor hc = palette.getColor(fontColor);
//                //sb.append("font-weight:" + boldWeight + ";"); // 字体加粗
//                if(isBold) {
//                    sb.append("font-weight: bold;"); // 字体加粗
//                }
//                sb.append("font-size: " + hf.getFontHeight() / 2 + "%;"); // 字体大小
//                String fontColorStr = convertToStardColor(hc);
//                if (fontColorStr != null && !"".equals(fontColorStr.trim())) {
//                    sb.append("color:" + fontColorStr + ";"); // 字体颜色
//                }
//
//                int topRow = cell.getRowIndex(),topColumn = cell.getColumnIndex();
//                if(map[0].containsKey(topRow + "," + topColumn)){
//                    //该单元格为合并单元格，宽度需要获取所有单元格宽度后合并
//                    String value = (String)map[0].get(topRow + "," + topColumn);
//                    String[] ary = value.split(",");
//                    int bottomColumn = Integer.parseInt(ary[1]);
//                    if(topColumn != bottomColumn){//合并列，需要计算相应宽度
//                        int columnWidth = 0;
//                        for(int i = topColumn; i <= bottomColumn; i++){
//                            columnWidth += sheet.getColumnWidth(i);
//                        }
//                        sb.append("width:" + columnWidth / 256 * hf.getFontHeight() / 20 + "pt;");
//                    }else{
//                        int columnWidth = sheet.getColumnWidth(cell.getColumnIndex()) ;
//                        sb.append("width:" + columnWidth / 256 * hf.getFontHeight() / 20 + "pt;");
//                    }
//                }else{
//                    int columnWidth = sheet.getColumnWidth(cell.getColumnIndex()) ;
//                    sb.append("width:" + columnWidth / 256 * hf.getFontHeight() / 20 + "pt;");
//                }
//
//                short bgColor = cellStyle.getFillForegroundColor();
//                hc = palette.getColor(bgColor);
//                String bgColorStr = convertToStardColor(hc);
//                if (bgColorStr != null && !"".equals(bgColorStr.trim())) {
//                    sb.append("background-color:" + bgColorStr + ";"); 		// 背景颜色
//                }
//                sb.append("border:solid #000000 1px;");
//            }
            sb.append("' ");
        }
    }

    /**
     * 计算宽度Width
     */
    private static int calcCellWidth(Workbook wb, Sheet sheet, Cell cell, Map<String, Object>[] map) {
        int columnWidth = 0;
        if (cell == null) {
            return columnWidth;
        }
        CellStyle cellStyle = cell.getCellStyle();
        if (cellStyle != null) {
            if (wb instanceof XSSFWorkbook) {
                XSSFFont xf = ((XSSFCellStyle) cellStyle).getFont();
                int topRow = cell.getRowIndex(), topColumn = cell.getColumnIndex();
                if (map[0].containsKey(topRow + "," + topColumn)) {
                    //该单元格为合并单元格，宽度需要获取所有单元格宽度后合并
                    String value = (String) map[0].get(topRow + "," + topColumn);
                    String[] ary = value.split(",");
                    int bottomColumn = Integer.parseInt(ary[1]);
                    if (topColumn != bottomColumn) {
                        //合并列，需要计算相应宽度
                        for (int i = topColumn; i <= bottomColumn; i++) {
                            columnWidth += sheet.getColumnWidth(i);
                        }
                        //columnWidth = columnWidth/256*xf.getFontHeight()/20;
                    } else {
                        columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
                        //columnWidth = columnWidth/256*xf.getFontHeight()/20;
                    }
                } else {
                    columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
                    //columnWidth = columnWidth/256*xf.getFontHeight()/20;
                }
            } else if (wb instanceof HSSFWorkbook) {
                HSSFFont hf = ((HSSFCellStyle) cellStyle).getFont(wb);
                int topRow = cell.getRowIndex(), topColumn = cell.getColumnIndex();
                if (map[0].containsKey(topRow + "," + topColumn)) {
                    //该单元格为合并单元格，宽度需要获取所有单元格宽度后合并
                    String value = (String) map[0].get(topRow + "," + topColumn);
                    String[] ary = value.split(",");
                    int bottomColumn = Integer.parseInt(ary[1]);
                    if (topColumn != bottomColumn) {//合并列，需要计算相应宽度
                        for (int i = topColumn; i <= bottomColumn; i++) {
                            columnWidth += sheet.getColumnWidth(i);
                        }
                        //columnWidth = columnWidth / 256 * hf.getFontHeight() / 20;
                    } else {
                        columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
                        //columnWidth = columnWidth / 256 * hf.getFontHeight() / 20;
                    }
                } else {
                    columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
                    //columnWidth = columnWidth / 256 * hf.getFontHeight() / 20;
                }
            }
        }
        //像素转excel中高度转换率
        //double PX_TO_EXCEL_HEIGHT = 15;
        //像素转excel中宽度转换率
        double PX_TO_EXCEL_WIDTH = 37.5;
        return (int) (columnWidth / 37.5);
    }

    /**
     * 单元格内容的水平对齐方式
     *
     * @param alignment
     * @return
     */
    private static String convertAlignToHtml(short alignment) {
        String align = "left";
        if (alignment == HorizontalAlignment.RIGHT.getCode()) {
            align = "right";
        } else if (alignment == HorizontalAlignment.LEFT.getCode()) {
            align = "left";
        } else if (alignment == HorizontalAlignment.CENTER.getCode()) {
            align = "center";
        } else if (alignment == HorizontalAlignment.CENTER_SELECTION.getCode()) {
            align = "center";
        } else if (alignment == HorizontalAlignment.DISTRIBUTED.getCode()) {
            align = "center";
        } else if (alignment == HorizontalAlignment.FILL.getCode()) {
            align = "center";
        } else if (alignment == HorizontalAlignment.JUSTIFY.getCode()) {
            align = "center";
        } else if (alignment == HorizontalAlignment.GENERAL.getCode()) {
            align = "left";
        } else {
            align = "left";
        }
//        switch (alignment) {
//            case 1: // CellStyle.ALIGN_LEFT:  HorizontalAlignment.LEFT
//                align = "left";
//                break;
//            case 2: //CellStyle.ALIGN_CENTER:
//                align = "center";
//                break;
//            case 3: //CellStyle.ALIGN_RIGHT:
//                align = "right";
//                break;
//            default:
//                break;
//        }
        return align;
    }

    /**
     * 单元格中内容的垂直排列方式
     *
     * @param verticalAlignment
     * @return
     */
    private static String convertVerticalAlignToHtml(short verticalAlignment) {
        String valign = "middle";
        switch (verticalAlignment) {
            case 2: //CellStyle.VERTICAL_BOTTOM:  VerticalAlignment.BOTTOM
                valign = "bottom";
                break;
            case 1: //CellStyle.VERTICAL_CENTER:
                valign = "center";
                break;
            case 0: //CellStyle.VERTICAL_TOP:
                valign = "top";
                break;
            default:
                break;
        }
        return valign;
    }

}
